import time, sys
import tinyos
import json
from datetime import datetime
from Queue import Queue
from multiprocess import Process

# ----------------------------------------------------------------------------- 
# Serial Interface
# ----------------------------------------------------------------------------- 
class ShellMessage(tinyos.Packet):

    Type = 0x06
    _message_format = """{
        "id":%d,
        "acceleration":%f,
        "date":"%s",
        "hits":%d}""".replace('\n','').replace('        ','') + '\r\n' 

    def __init__(self, packet = None):
        ''' Initialize a new instance of the ShellMessage

        :param packet: The packet to parse
        '''
        settings = [
            ('id',       'int', 2),
            ('counter',  'int', 2),
            ('readings', 'blob', None)]
        tinyos.Packet.__init__(self, settings, packet)

    def parse(self):
        ''' Return the parsed data packet

        :returns: The parsed data packet as a dict
        '''
        values = [(i<<8 | j) for (i,j) in zip(self.readings[::2], self.readings[1::2])]
        parameters = (10, values[0], datetime.now(), self.counter)
        return self._message_format % parameters


class SerialGenerator(object):

    def __init__(self):
       sys.argv = ['', 'serial@/dev/ttyUSB0:115200']
       self.messages = tinyos.AM()

    def __iter__(self):
        return self

    def next(self):
        packet = self.messages.read()
        if packet and (packet.type == ShellMessage.Type):
            message = ShellMessage(packet.data)
            return message.parse()

# ----------------------------------------------------------------------------- 
# Web Interface
# ----------------------------------------------------------------------------- 
connections = []
def main_reader():
    generator = SerialGenerator()
    # insert messages in database async
    for message in generator:
        for queue in connections:
            queue.put_nowait(message)

def main(environ, start_response):
    queue = Queue()
    connections.append(queue)
    data = 'something'
    status = '200 OK'
    response_headers = [
        ('Content-Type', 'application/json'),
        ('Transfer-Encoding', 'chunked')
    ]
    try:
        start_response(status, response_headers)
        return iter(queue.get, None)
    except ex: connections.remove(queue)
